package com.suyuan.controller.shop;

import com.suyuan.entity.CompanyInfo;
import com.suyuan.service.CompanyService;
import com.suyuan.utils.JsonMsg;
import com.suyuan.utils.JsonUtils;
import com.suyuan.vo.CompanyVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 企业控制类
 */
@Controller
@RequestMapping(value = "/shop/comp")
public class CompController {

    @Resource(name = "companyService")
    private CompanyService companyService;

    /**
     * 首页推荐商家列表(随机推荐4个)
     *
     */
    @RequestMapping(value = "/recommCompany")
    @ResponseBody
    public Object recommCompany(){
        List<CompanyVO> all = companyService.findALLInfo();
        List<CompanyVO> result = new ArrayList<CompanyVO>();

        int size = all.size();
        if(size >= 4){
            //史上最牛逼的大数据推荐算法
            Random random = new Random();
            while(true){
                CompanyVO companyVO = all.get(random.nextInt(size));
                if(!result.contains(companyVO)){
                    result.add(companyVO);//防止添加进同一个公司信息
                }
                if(result.size() == 4){
                    break;//添加够四个跳出循环
                }
            }
        }else{
            return JsonMsg.SuccessMsg(all);
        }
        return JsonMsg.SuccessMsg(result);
    }

    /**
     * 公司详情
     *
     */
    @RequestMapping(value = "/findComById")
    @ResponseBody
    public Object findComById(@RequestBody String data){
        CompanyInfo company = JsonUtils.jsonToPojo(data,CompanyInfo.class);
        if(company.getGid() == null){
            return JsonMsg.ErrorMsg("参数不能为空");
        }
        CompanyInfo companyInfo = companyService.companyDetail(company.getGid());
        if(companyInfo != null){
            return JsonMsg.SuccessMsg(companyInfo);
        }
        return JsonMsg.ErrorMsg("你查找的公司不存在");
    }

}
